from django.db import close_old_connections
from channels.security.websocket import WebsocketDenier
from system.user.models import Users
# from utils import get_request_real_ip
from urllib.parse import parse_qs
import time
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import AccessToken
from rest_framework_simplejwt.authentication import default_user_authentication_rule
from rest_framework_simplejwt.exceptions import InvalidToken
import logging

logger = logging.getLogger(__name__)


class AuthMiddleware:
    def __init__(self, application):
        self.application = application

    def __call__(self, scope):
        # Make sure the scope is of type websocket
        if scope["type"] != "websocket":
            raise ValueError(
                "You cannot use AuthMiddleware on a non-WebSocket connection"
            )
        headers = dict(scope.get('headers', []))
        if self.verify_user(scope, headers):
            return self.application(scope)
        else:
            return WebsocketDenier(scope)

    # def get_real_ip(self, headers):
    #     decode_headers = {
    #         'x-forwarded-for': headers.get(b'x-forwarded-for', b'').decode(),
    #         'x-real-ip': headers.get(b'x-real-ip', b'').decode()
    #     }
    #     return get_request_real_ip(decode_headers)

    def get_raw_token(self, scope):
        query_string = scope['query_string'].decode()
        return parse_qs(query_string).get('x-token', [''])[0]

    def verify_user(self, scope, headers):
        close_old_connections()
        # x_real_ip = self.get_real_ip(headers)
        token = self.get_raw_token(scope)
        try:
            validated_token = JWTAuthentication().get_validated_token(raw_token=token)
        except InvalidToken as e:
            logger.error(e)
            return False
        user = JWTAuthentication().get_user(validated_token)
        if user and user.is_active:
            scope['user'] = user
            return True
